package team.seekers.catering.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.seekers.catering.common.result.R;
import team.seekers.catering.common.result.ResultCode;
import team.seekers.catering.community.entity.dao.Post;
import team.seekers.catering.community.entity.dto.add.PostAddDTO;
import team.seekers.catering.community.entity.dto.query.PostQuery;
import team.seekers.catering.community.entity.dto.update.LikeOrCommentUpdateDTO;
import team.seekers.catering.community.entity.dto.update.PostUpdateDTO;
import team.seekers.catering.community.entity.vo.info.PostInfoVO;
import team.seekers.catering.community.service.PostService;

import java.util.Map;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    /**
     * 增加一个帖子
     */
    @PostMapping("/add")
    public R add(@RequestBody PostAddDTO postAddDTO){
        String id = postService.add(postAddDTO);
        return R.success().data("id",id);
    }

    /**
     * 根据id删除一个帖子
     */
    @GetMapping("/delete/{postId}")
    public R delete(@PathVariable("postId")String id){
        postService.delete(id);
        return R.success();
    }

    /**
     * 修改一个帖子(题目和内容)
     */
    @PostMapping("/updateMain")
    public R updateMain(@RequestBody PostUpdateDTO postUpdateDTO){
        String id = postService.updateMain(postUpdateDTO);
        return R.success().data("id",id);
    }

    /**
     * 修改一个帖子(点赞和评论)
     */
    @PostMapping("/updateForLikeOrComment")
    public R updateForLikeOrComment(@RequestBody LikeOrCommentUpdateDTO likeOrCommentUpdateDTO){
        String id = postService.updateForLikeOrComment(likeOrCommentUpdateDTO);
        return R.success().data("id",id);
    }

    /**
     * 根据id查询一个帖子
     */
    @GetMapping("/query/{postId}")
    public R query(@PathVariable("postId")String id){
        PostInfoVO postInfoVO = postService.get(id);
        return R.success().data("info", postInfoVO);
    }

    /**
     * 分页查询帖子
     */
    @PostMapping("/adminPagePost/{current}/{limit}")
    public R adminPagePost(@PathVariable("current") long current,
                              @PathVariable("limit") long limit,
                              @RequestBody PostQuery query){
        QueryWrapper<Post> wrapper = new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(query.getNameKey())){
            wrapper.like("name",query.getNameKey());
        }
        Map<String, Object> map = postService.adminPagePost(current,limit,wrapper);
        if(map == null){
            return R.fail(ResultCode.GET_FAIL);
        }
        return R.success(map);
    }
}
